package com.ruoyi.modbus.Task;

import com.ruoyi.modbus.domain.PlcInfo;
import com.ruoyi.modbus.handler.ModbusTcpNettyMaster;
import net.wimpi.modbus.net.TCPMasterConnection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.net.InetAddress;
import java.util.Arrays;
import java.util.List;

@Component
public class PlcStatusScheduler {
    private static final Logger logger = LoggerFactory.getLogger(PlcStatusScheduler.class);

    // 多台PLC的IP和端口
    private static final List<PlcInfo> PLC_LIST = Arrays.asList(
            new PlcInfo("127.0.0.1", 502),
            new PlcInfo("192.168.1.11", 502)
    );

    @Scheduled(cron = "*/2 * * * * ?")
    public void getPlcStatusAtNoon() {
        logger.info("定时任务开始：每12秒获取所有PLC状态");
        for (PlcInfo plc : PLC_LIST) {
            try {
                TCPMasterConnection connection = new TCPMasterConnection(InetAddress.getByName(plc.getHost()));
                connection.setPort(plc.getPort());
                connection.connect();
                ModbusTcpNettyMaster.sendCustomMessage(connection,plc);
                connection.close();
            } catch (Exception e) {
                logger.error("定时获取PLC[{}:{}]状态失败: {}", plc.getHost(), plc.getPort(), e.getMessage());
            }
        }
    }

}